<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px" @submit.native.prevent="() => handleQuery()">
            <el-form-item label="签约主体" prop="clientName">
                <el-select v-model="queryParams.roleId" clearable :placeholder="$t('please_select', { name: '' })">
                    <el-option v-for="item in [{ label: '全部', value: '1' }]" :key="item.id" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发送日期" prop="clientName">
                <el-date-picker v-model="queryParams.date" type="date" placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="签约日期" prop="clientName">
                <el-date-picker v-model="queryParams.date" type="date" placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="签约状态" prop="clientName">
                <el-select v-model="queryParams.roleId" clearable :placeholder="$t('please_select', { name: '' })">
                    <el-option v-for="item in [{ label: '全部', value: '1' }]" :key="item.id" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search")
                    }}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
            $t("reset")
        }}</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['custom:customerList:add']">新增签约合同</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain  size="mini" 
                    v-hasPermi="['custom:customerList:export']">批量下载附件</el-button>
            </el-col>
          

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="clientList" border @selection-change="handleSelectionChange"
            :max-height="tableHeight">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" label="序号" width="55">
            </el-table-column>
            <el-table-column label="合同名称" align="center" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="合同模板名称" align="center" prop="templateName" :show-overflow-tooltip="true" />
            <el-table-column label="签约人" align="center" prop="person" :show-overflow-tooltip="true" />
            <el-table-column label="发送日期" align="center" prop="date1" :show-overflow-tooltip="true" />
            <el-table-column label="签约日期" align="center" prop="date2" :show-overflow-tooltip="true" />
            
            <el-table-column label="合同状态" align="center" prop="status" :show-overflow-tooltip="true">
                <template slot-scope="{ row }">
                    <p v-if="row.status==0">待签约</p>
                    <p v-if="row.status==1">已签约</p>
                    <p v-if="row.status==2">已取消</p>
                    <p v-if="row.status==3">已过期</p>
                    <p v-if="row.status==4">已失效</p>
                </template>
            </el-table-column>
            <!-- <el-table-column
          :label="$t('employer_data')"
          align="center"
          prop="employerNum"
          :show-overflow-tooltip="true"
        /> -->
            <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width" width="320">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleView(scope.row)"
                        v-hasPermi="['custom:customerList:view']">详情</el-button>
                    <el-button size="mini" type="text"  @click="handleUpdate(scope.row)"
                        v-hasPermi="['custom:customerList:edit']" v-if="scope.row.status==1">下载</el-button>
                    
                   
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" :page-sizes="[10, 20, 30, 50, 100, 200]" />

        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
                <el-card class="box-card" style="margin-bottom: 20px">
                    <div slot="header" class="clearfix">
                        <span>{{ $t("basic_information") }}</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item :label="$t('profie_picture')" prop="avatar">
                                <image-upload v-model="form.avatar" :limit="1" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('client_name')" prop="clientName">
                                <el-input v-model="form.clientName" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('client_code')" prop="clientCode">
                                <el-input v-model="form.clientCode" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item :label="$t('country_region')" prop="countryRegion">
                                <el-input v-model="form.countryRegion"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('default_language')" prop="language">
                                <el-select v-model="form.language" :placeholder="$t('please_select', { name: '' })">
                                    <el-option v-for="dict in dict.type.language_type" :key="dict.value"
                                        :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item :label="$t('legal_representative')" prop="legalPerson">
                                <el-input v-model="form.legalPerson" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('license_type')" prop="certificateType">
                                <el-select v-model="form.certificateType"
                                    :placeholder="$t('please_select', { name: '' })">
                                    <el-option v-for="dict in dict.type.id_card_type" :key="dict.value"
                                        :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('license_number')" prop="certificateNumber">
                                <el-input v-model="form.certificateNumber"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('office_address')" prop="officeAddress">
                                <el-input v-model="form.officeAddress"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('contact_person')" prop="contactPerson">
                                <el-input v-model="form.contactPerson"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('contact_phone_number')" prop="contactPhone">
                                <el-input v-model="form.contactPhone" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('email_address')" prop="email">
                                <el-input v-model="form.email" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('business_license_number')" prop="licenseNum">
                                <el-input v-model="form.licenseNum" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('fax_number')" prop="faxNumber">
                                <el-input v-model="form.faxNumber" :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="box-card" style="margin-bottom: 20px">
                    <div slot="header" class="clearfix">
                        <span>{{ $t("bank_information") }}</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item :label="$t('bank_account_number')" prop="bankDTO.bankAccount">
                                <el-input v-model="form.bankDTO.bankAccount"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('account_holder')" prop="bankDTO.accountHolder">
                                <el-input v-model="form.bankDTO.accountHolder"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('bank_code')" prop="bankDTO.bankCode">
                                <el-input v-model="form.bankDTO.bankCode"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('branch_code')" prop="bankDTO.branchCode">
                                <el-input v-model="form.bankDTO.branchCode"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('bank_name_of_opening_account')" prop="bankDTO.openingBank">
                                <el-input v-model="form.bankDTO.openingBank"
                                    :placeholder="$t('please_enter', { name: '' })" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('permission_of_default_bank_account')"
                                prop="bankDTO.defaultAccount">
                                <el-select v-model="form.bankDTO.defaultAccount"
                                    :placeholder="$t('please_select', { name: '' })">
                                    <el-option v-for="dict in dict.type.yes_or_no" :key="dict.value" :label="dict.label"
                                        :value="parseInt(dict.value)"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="16">
                <el-form-item label="备注" prop="bankDTO.remark">
                  <el-input v-model="form.bankDTO.remark" placeholder="请输入备注" maxlength="300" type="textarea" :rows="3"
                    :show-word-limit="true" />
                </el-form-item>
              </el-col> -->
                    </el-row>
                </el-card>
                <el-card class="box-card" style="margin-bottom: 20px">
                    <div slot="header" class="clearfix">
                        <span>{{ $t("settings") }}</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item :label="$t('customManager')" prop="chargePerson">
                                <div @click="handleCheckHead">
                                    <el-input :placeholder="$t('please_select', { name: '' })"
                                        v-model="form.chargePersonName" readonly>
                                        <el-button slot="append" icon="el-icon-search"></el-button>
                                    </el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{
            $t("confirm")
        }}</el-button>
                <el-button @click="cancel">{{ $t("cancel") }}</el-button>
            </div>
        </el-dialog>
        <!-- 配置权限对话框 -->
        <el-dialog :title="$t('set_permissions')" :visible.sync="authOpen" width="500px" append-to-body>
            <el-form ref="authForm" :model="authForm" label-width="100px">
                <el-form-item :label="$t('menu_permissions')">
                    <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">{{
            $t("expand_collapse")
        }}</el-checkbox>
                    <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">{{
            $t("elect_all_don_select_all") }}</el-checkbox>
                    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id"
                        empty-text="loading.." :props="defaultProps"></el-tree>
                </el-form-item>
                <el-form-item :label="$t('remarks')">
                    <el-input v-model="authForm.remark" type="textarea"
                        :placeholder="$t('please_enter', { name: '' })"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="authSubmitForm">{{
                    $t("confirm")
                    }}</el-button>
                <el-button @click="authCancel">{{ $t("cancel") }}</el-button>
            </div>
        </el-dialog>

        <!-- 导入弹窗 -->
        <importModal ref="importModal" :title="$t('import')" downloadUrl="business/client/downloadTemplate.do"
            uploadUrl="business/client/importTemplate.do" downloadName="employer" @refreshList="getList"></importModal>

        <!-- 选择负责人弹窗 -->
        <headModal ref="headModal" @setHeadData="setHeadData"></headModal>

        <!-- 客户详情弹窗 -->
        <customerDetail ref="customerDetail"></customerDetail>
    </div>
</template>

<script>
const hongKong = /[A-Za-z]{1}\\d{6}[(\\d)|A]{3}/;
const maCao = /[1|5|7]\\d{6}[(\\d)]{3}/;
const taiWan = /[A-Z]{1}\\d{9}/;
const Dalu = /([1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3})/;

import {
    listClient,
    getClient,
    delClient,
    addClient,
    updateClient,
    permissionSettings,
    getUsermenuTree,
    clientEmployerMenuTree,
} from "@/api/custom/customerList";
import { treeselect } from "@/api/system/menu.js";
import { clientResetPwd } from "@/api/system/user";
import importModal from "@/views/components/custom/importModal.vue";
import headModal from "@/views/components/custom/headModal.vue";
import customerDetail from "./detail.vue";
import {
    userAble,
    userClientAble,
} from "@/api/custom/employerList";
export default {
    name: "Client",
    dicts: ["id_card_type", "language_type", "yes_or_no"],
    components: {
        importModal,
        headModal,
        customerDetail,
    },
    data() {
        return {
            selection: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 客户管理表格数据
            clientList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                clientName: null,
            },
            // 表单参数
            form: {
                bankDTO: {},
            },
            // 表单校验
            rules: {
                clientName: [
                    {
                        required: true,
                        message: this.$t("cannot_empty", { name: this.$t("client_name") }),
                        trigger: "blur",
                    },
                ],
                clientCode: [
                    {
                        required: true,
                        message: this.$t("cannot_empty", { name: this.$t("client_code") }),
                        trigger: "blur",
                    },
                ],
                email: [
                    {
                        required: true,
                        pattern:
                            /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                        message: this.$t("correct_format"),
                        trigger: ["blur"],
                    },
                ],
                contactPhone: [
                    {
                        pattern:
                            /^((\+|00)86)?1[3-9]\d{9}$|^852\d{8}$|^853\d{8}$|^(886|0)9\d{8}$/,
                        message: this.$t("correct_format"),
                        trigger: ["blur"],
                    },
                ],
            },
            //权限弹窗
            authOpen: false,
            //权限表单
            authForm: {
                menuIdList: [],
            },
            // 是否显示弹出层（数据权限）
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            defaultProps: {
                children: "children",
                label: (data) => this.$t(data.label),
            },
            // 菜单列表
            menuOptions: [],
        };
    },
    created() {
        this.getList();
    },
    methods: {
        handleBatcheDel() {
            if (this.ids.length === 0) return this.$message.warning(this.$t("please_select", { name: this.$t("data_source") }))
            this.handleDelete({})
        },
        /**
         * 
         * @param {禁用启用} row 
         */
        handleStop(row) {
            let name = "";
            if (row.status == "0") {
                name = this.$t("disable");
            } else {
                name = this.$t("enable");
            }
            this.$modal
                .confirm(this.$t("enable_disable_data", { name }))
                .then(function () {
                    return userClientAble(row.id);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(this.$t("operation_successful"));
                })
                .catch(() => { });
        },
        /** 查询客户管理列表 */
        getList() {
            this.loading = true;
            listClient(this.queryParams).then((response) => {
                // this.clientList = response.data.records;
                this.clientList = [
                    {
                        name:'劳动合同',
                        templateName:'模板一',
                        person:'张三',
                        date1:'2020-12-23',
                        date2:'2020-12-23',
                        status:0
                    },
                    {
                        name:'劳动合同',
                        templateName:'模板一',
                        person:'张三',
                        date1:'2020-12-23',
                        date2:'2020-12-23',
                        status:1
                    },
                    {
                        name:'劳动合同',
                        templateName:'模板一',
                        person:'张三',
                        date1:'2020-12-23',
                        date2:'2020-12-23',
                        status:2
                    },
                    {
                        name:'劳动合同',
                        templateName:'模板一',
                        person:'张三',
                        date1:'2020-12-23',
                        date2:'2020-12-23',
                        status:3
                    },
                    {
                        name:'劳动合同',
                        templateName:'模板一',
                        person:'张三',
                        date1:'2020-12-23',
                        date2:'2020-12-23',
                        status:4
                    },
                ]
                // this.total = response.data.total;
                this.total = 5
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 取消按钮
        authCancel() {
            this.authOpen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                headPortrait: null,
                clientName: null,
                clientCode: null,
                countriesRegions: null,
                defaultLanguage: null,
                legalPerson: null,
                certificateType: null,
                officeAddress: null,
                contactPerson: null,
                email: null,
                faxNumber: null,
                idNumber: null,
                contactPhone: null,
                principal: null,
                bankDTO: {
                    bankAccount: null,
                    accountHolder: null,
                    bankCode: null,
                    branchCode: null,
                    openingBank: null,
                    defaultAccount: null,
                    remark: null,
                },
            };
            this.resetForm("form");
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([]);
            }
            this.menuExpand = false;
            this.menuNodeAll = false;
            this.deptExpand = true;
            this.deptNodeAll = false;
            this.authForm = {
                menuIdList: [],
            };
            this.resetForm("authForm");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 树权限（展开/折叠）
        handleCheckedTreeExpand(value, type) {
            if (type == "menu") {
                let treeList = this.menuOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
                }
            } else if (type == "dept") {
                let treeList = this.deptOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll(value, type) {
            if (type == "menu") {
                this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
            } else if (type == "dept") {
                this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
            }
        },
        // 所有菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();

            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = this.$t("add_new_client");
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getClient(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = this.$t("edit");
            });
        },
        // 查看
        handleView(row) {
            this.reset();
            this.$refs.customerDetail.handleView(row);
        },
        /** 重置密码按钮操作 */
        handleReset(row) {
            this.reset();
            const id = row.id;
            this.$modal
                .confirm(this.$t("customer_password"))
                .then(function () {
                    return clientResetPwd(id);
                })
                .then(() => {
                    this.$modal.msgSuccess(this.$t("operation_successful"));
                })
                .catch(() => { });
        },
        /** 设置按钮 */
        handleSet(row) {
            this.reset();
            this.getUsermenuTree(row.id);
            this.authForm = row;
            this.authOpen = true;
        },
        getUsermenuTree(id) {
            clientEmployerMenuTree(id).then((response) => {
                this.authForm.remark = response.remark;
                this.menuOptions = response.menus;
                let checkedKeys = response.checkedKeys;
                checkedKeys.forEach((v) => {
                    this.$nextTick(() => {
                        this.$refs.menu.setChecked(v, true, false);
                    });
                });
            });
        },
        /** 设置权限提交 */
        authSubmitForm() {
            this.authForm.menuIdList = this.getMenuAllCheckedKeys();
            let data = {
                businessId: this.authForm.id,
                menuIds: this.authForm.menuIdList,
                remark: this.authForm.remark,
            };
            permissionSettings(data).then((response) => {
                this.$modal.msgSuccess(this.$t("operation_successful"));
                this.authOpen = false;
                this.getList();
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.bankVO = this.form.bankDTO;
                    if (this.form.id != null) {
                        updateClient(this.form).then((response) => {
                            this.$modal.msgSuccess(this.$t("operation_successful"));
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addClient(this.form).then((response) => {
                            this.$modal.msgSuccess(this.$t("operation_successful"));
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm(this.$t("delete_data"))
                .then(function () {
                    return delClient(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(this.$t("operation_successful"));
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "business/client/export",
                {
                    ...this.queryParams,
                },
                `client_${new Date().getTime()}.xlsx`
            );
        },
        /** 导入按钮操作 */
        handleImport() {
            this.$refs.importModal.showModal();
        },
        // 选择负责人
        handleCheckHead() {
            this.$refs.headModal.showModal();
        },
        setHeadData(value) {
            if (value) {
                this.form.chargePerson = value.userId;
                this.$set(this.form, "chargePersonName", value.nickName);
            } else {
                this.form.chargePerson = null;
            }
        },
    },
};
</script>